﻿// JScript 文件
// JScript 文件

var owner;                   //opensocial.Person
var viewer;                  //opensocial.Person
var ownerFriends;            // opensocial.Collection
var ownerFriendsStarBless;   // 类型：{id: {'starBless': json}}
var ownerStarBless;          //{'starBless':json}
var starFrame_x;             //opensocial.Collection
var starFrame_y;             //opensocial.Collection
        
/* Gadget 执行入口 */
function init()
{
  preload();
  reloadAll();
  storyHandle();
};
gadgets.util.registerOnLoadHandler(init);

/* 发送 Opensocial API 请求 */
function reloadAll() 
{
  var req = new opensocial.DataRequest();
  
  req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER), 'v')
  req.add(req.newFetchPersonRequest('OWNER'), 'o');
  req.add(req.newFetchPeopleRequest('OWNER_FRIENDS'), 'vf');
  
  req.add(req.newFetchPersonAppDataRequest('OWNER', 'starFrame_x'), 'sx');
  req.add(req.newFetchPersonAppDataRequest('OWNER', 'starFrame_y'), 'sy');
  
  req.add(req.newFetchPersonAppDataRequest('OWNER', 'starBless'), 'sb');
  req.add(req.newFetchPersonAppDataRequest('OWNER_FRIENDS', 'starBless'), 'vfs');
            
  req.send(onReloadAll);
};
        
/* 处理 Opensocial API 响应 */
function onReloadAll(dataResponse) 
{
  // 获取数据 
  viewer = dataResponse.get('v').getData() || {};
  owner = dataResponse.get('o').getData() || {};
  
  ownerFriends = dataResponse.get('vf').getData() || {};
  
  starFrame_x = dataResponse.get('sx').getData()[owner.getId()] || {};
  starFrame_y = dataResponse.get('sy').getData()[owner.getId()] || {};
  
  ownerStarBless = dataResponse.get('sb').getData()[owner.getId()] || {};
  ownerFriendsStarBless = dataResponse.get('vfs').getData() || {};
  
          
  //显示数据
   initStarsFrame();
   showStars();
   showStars_User();
   showOwnerBless();
}
        
/*显示星座*/
function initStarsFrame()
{  
  // 初始化坐标数组
  for(var i=0;i<imaxStars;i++)
  {
	 istarFrame_x[i]=-1;
     istarFrame_y[i]=-1;
  }
  // 解析星座坐标数据 
  var jsonx = starFrame_x['starFrame_x'];
  var jsony = starFrame_y['starFrame_y'];
  var jx;
  var jy;
  try  {
    jx = gadgets.json.parse(gadgets.util.unescapeString(jsonx)) || [];
    jy = gadgets.json.parse(gadgets.util.unescapeString(jsony)) || [];
  } catch(e) {
    jx = [];jy=[];
  }
  var len = jx.length;
  iusedStars=len;
  for (var i = 0; i < len; ++i) {
    istarFrame_x[i]=jx[i];
    istarFrame_y[i]=jy[i];
  }
}
        
/*显示用户已经定义好的星星并获取照片地址*/
function showStars_User()
{
  if(iusedStars==0)
  	return;
  var str_1="<tr>";		//许愿人的照片
  var str_2="<tr>";		//许愿人的姓名
  var flag;
  var starBless;
  
  /* 遍历owner每个朋友 */
  for (var friendId in ownerFriendsStarBless) {
    flag=true;
    var data = ownerFriendsStarBless[friendId];
    var friend = ownerFriends.getById(friendId);
    
    /* 解析朋友的星愿数据 */
    var json = data['starBless'];
    starBless = [];
    try  {
      starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
    } catch(e) {
      starBless = [];
    }

    for(var i=0;i<starBless.length;i++)
    {
        var s=starBless[i].split('|');
        //如果在owner这里许过星愿
        if(s[0]==owner.getId())
        {
            if(flag)
            {
                str_1=str_1+"<td><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" onclick=locateUerBless("+friendId+"); /></td>";
                str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
                flag=false;
            }
            var obj=document.getElementById("star"+s[1]);
            obj.style.visibility="visible";
            var str="userStarOnmouseover("+s[1]+")";
            obj.onmouseover=Function(str);
            obj=document.getElementById("info"+s[1]);
            obj.value=starBless[i];
            document.getElementById("img"+s[1]).src=imgs[parseInt(s[3])+7].src;
        }
    }
  }
          
  /*遍历自己的星愿*/
  var jownerStarBless=ownerStarBless['starBless'];
  try  {
      starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
    } catch(e) {
      starBless = [];
  }
  flag=true;
  for(var i=0;i<starBless.length;i++)
  {
      var s=starBless[i].split('|');
      
      //如果自己在自己这里许过愿
      if(s[0]==owner.getId())	
      {
          if(flag)
          {
              str_1=str_1+"<td><img src="+owner.getField(opensocial.Person.Field.THUMBNAIL_URL)+"  onclick=locateUerBless("+owner.getId()+") /></td>";
              str_2=str_2+"<td>"+owner.getDisplayName()+"</td>";
              flag=false;
          }
          var obj=document.getElementById("star"+s[1]);
          obj.style.visibility="visible";
          var str="userStarOnmouseover("+s[1]+")";
          obj.onmouseover=Function(str);
          obj=document.getElementById("info"+s[1]);
          obj.name=owner.getId();
          obj.value=starBless[i];
          document.getElementById("img"+s[1]).src=imgs[parseInt(s[3])+7].src;
      }
  }  
 var obj=document.getElementById("divBlessFriends");
 obj.innerHTML="<table cellspacing=2>"+str_1+"</tr>"+str_2+"</tr>"+"</table>";
}
        
/*获取拥有者owner在别处的祝福*/
function showOwnerBless()
{
  var jownerStarBless=null;
  if(ownerStarBless!=null)
     jownerStarBless=ownerStarBless['starBless'];
  try  {
      starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
    } catch(e) {
      starBless = [];
  }
  
  var flag;
  var s;
  var str_1="<tr>";
  var str_2="<tr>";
  var friend;
  
  if(starBless.length>=1)
  {
    s=starBless[0].split('|');
    flag=s[0];
    if(s[0]!=owner.getId())
        friend = ownerFriends.getById(s[0]);
    else
        friend = owner;
    str_1=str_1+"<td><a href="+friend.getField(opensocial.Person.Field.PROFILE_URL)+" target=_blank><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" border=0/></a></td>";
    str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
  }
  
  for(var i=1;i<starBless.length;i++)
  {
      var s=starBless[i].split('|');
      if(s[0]!=flag)
      {
          if(s[0]!=owner.getId())
            friend = ownerFriends.getById(s[0]);
          else
            friend = owner;
        str_1=str_1+"<td><img src="+friend.getField(opensocial.Person.Field.THUMBNAIL_URL)+" /></td>";
        str_2=str_2+"<td>"+friend.getDisplayName()+"</td>";
        flag=s[0];
      }
   }
 var obj=document.getElementById("divOwnerBless");
 obj.innerHTML="<table cellspacing=2>"+str_1+"</tr>"+str_2+"</tr>"+"</table>";
}
        
        
 /* 处理坐标保存事件 */
function onSave_frame() 
{
  setStatus(document.getElementById('frameProcess'),'正在保存星座中....');
  //保存用户的星座坐标
  var starBless;
  var json_x = gadgets.json.stringify(istarFrame_x);
  var json_y = gadgets.json.stringify(istarFrame_y);
  var req = opensocial.newDataRequest();
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starFrame_x', json_x));
  req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starFrame_y', json_y));
  
      req.send(function(dataResponse) {
        postBlessActivity("修改了自己的星座");
        starFrameHandle();
        setStatus(document.getElementById('frameProcess'),'保存成功！');
      });
};
        
/*修改自己的祝福*/
function alterSelfBless(text)
{
    if(icurrStarId==-1)
        return;
    setStatus(document.getElementById('viewerProcess'),'正在保存星愿中....');
    var s=document.getElementById("info"+icurrStarId).value;
    var sp=s.split('|');
    var starBless;
    var json;
    
    //如果查看者是owner
    if(viewer.isOwner())
    {
       json=ownerStarBless['starBless'];
       try  {
          starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
          } catch(e) {
          starBless = [];
        }
        var j=0;
        text=sp[0]+"|"+sp[1]+"|"+text+"|"+owner.getId();
        while(j<starBless.length && starBless[j]!=s)   ++j;
        starBless[j]=text;
    }
    //查看者不是owner
    else
    {
        var friendId=viewer.getId();
        var data = ownerFriendsStarBless[friendId];                
        json = data['starBless'];
        try  {
           starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
         }catch(e) {
           starBless = [];
         }
        var j=0;
        text=sp[0]+"|"+sp[1]+"|"+text+"|"+friendId;
        while(j<starBless.length && starBless[j]!=s)   ++j;
        starBless[j]=text;
    }
    
   json= gadgets.json.stringify(starBless);
    /* 发送更新数据请求 */
   var req = opensocial.newDataRequest();
   req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));           
   req.send(function(dataResponse) {
   postBlessActivity( "在"+owner.getDisplayName()+" 那里修改了自己的星愿" );
    
    setStatus(document.getElementById('viewerProcess'),'保存成功！');
    viewerBlessHandle();   
   });
    
}
		
/*删除自己的所有星愿*/
function delAllSelfBless()
{
	if(!confirm("你确定要删除自己的所有星愿?"))
		return;
    setStatus(document.getElementById('ownerProcess'),'正在删除中....');
	if(viewer.isOwner())
	{
		 var req = opensocial.newDataRequest();
		 req.add(req.newRemovePersonAppDataRequest('VIEWER','starBless'));
		 req.send(function(dataResponse) {
     		postBlessActivity("删除了自己所有星愿");
     		
     		setStatus(document.getElementById('ownerProcess'),'删除成功！.');
     		ownerBlessHandle();
	     });
	}
}
        
/*删除自己的星愿*/
function deleteSelfBless()
{
   if(icurrStarId==-1)
        return;
	if(!confirm("确定要删除这个星愿?"))
		return;
    setStatus(document.getElementById('viewerProcess'),'正在删除中....');
    var s=document.getElementById("info"+icurrStarId).value;
    var starBless;
    var json;
    if(viewer.isOwner())
    {
       json=ownerStarBless['starBless'];
       try  {
          starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
          } catch(e) {
          starBless = [];
        }
        var j=0;
        while(j<starBless.length && starBless[j]!=s)   ++j;
        while(j<starBless.length-1) starBless[j]=starBless[++j];
        starBless.length--;
    }
    //查看者不是owner
    else
    {
        var friendId=viewer.getId();
        var data = ownerFriendsStarBless[friendId];                
        json = data['starBless'];
        try  {
           starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
         }catch(e) {
           starBless = [];
         }
        var j=0;
        while(j<starBless.length && starBless[j]!=s)   ++j;
        while(j<starBless.length-1) starBless[j]=starBless[++j];
        starBless.length--;
    }
     
    /* 发送更新数据请求 */
   var req = opensocial.newDataRequest();
   if(starBless.length>0)
   {
        json= gadgets.json.stringify(starBless);
        req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));
   }
   else
        req.add(req.newRemovePersonAppDataRequest('VIEWER','starBless'));
         
   req.send(function(dataResponse) {
     postBlessActivity( "在"+owner.getDisplayName()+" 那里删除了自己的一个星愿" );
    
     setStatus(document.getElementById('viewerProcess'),'删除成功！');
      viewerBlessHandle();
   });
        
} 

        
/*保存用户的自定义星星信息*/
function saveAddStar(text)
{
	//获取空闲的星座id
	var idstar;
	for(idstar=1;idstar<=imaxStars;idstar++)
	 {
		var obj=document.getElementById("star"+idstar);
		if(obj!=null)
		{				
		  obj=document.getElementById("img"+idstar);
		  if(obj.src==imgs[0].src || obj.src=="")
			 break;
		}
	 }
	 if(idstar>imaxStars)
	 {
		 alert("许愿星星已经用完!");
		 return;
	 }
	setStatus(document.getElementById('addProcess'),'正在提交星愿中....');
	 //开始构造数据text，并上传给服务器
	var oid=owner.getId();
    text=oid+"|"+idstar+"|"+text;
    var starBless;
    var json;
    if(viewer.isOwner())
    {
        text=text+"|"+oid;
        var jownerStarBless=ownerStarBless['starBless'];
        try  {
          starBless = gadgets.json.parse(gadgets.util.unescapeString(jownerStarBless)) || [];
          } catch(e) {
              starBless = [];
          }
    }
   else
   {
        var friendId=viewer.getId();
        var data = ownerFriendsStarBless[friendId];
        var friend = ownerFriends.getById(friendId);
        
        if(friend==null)
        {
            alert("只允许该应用安装者的好友使用！");
            return;
        }
        
        text=text+"|"+friendId;
        if(data!=null)
            json = data['starBless'];
        else
            json=null;
        try  {
           starBless = gadgets.json.parse(gadgets.util.unescapeString(json)) || [];
             }catch(e) {
               starBless = [];
             }
    }
    starBless.push(text);
    json= gadgets.json.stringify(starBless);
     
    //发送更新数据请求
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest('VIEWER', 'starBless', json));   
    req.send(function(dataResponse) {
    postBlessActivity( "在"+owner.getDisplayName()+" 那里许下了星愿" );
    addBlessHandle();
    setStatus(document.getElementById('addProcess'),'提交星愿成功！');
    starFly(idstar);
   });
}
        
/*发送祝福事件活动*/
function postBlessActivity(text) 
{  
    var title = text; 
    var params = {};  
    params[opensocial.Activity.Field.TITLE] = title;  
    var activity = opensocial.newActivity(params);  
    opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH,
    function() {
    /* 更新后刷新所有数据 */        
    reloadAll();});
}

